import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_ExamBean.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_page.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/study/exam_pc_page.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'mine_my_exam_details_page.dart';
import 'mine_my_pc_exam_recoder_page.dart';
import 'new/score/mine_my_score_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 4/4/21.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
///我的考试
class MineMyExamPage extends StatefulWidget {
  @override
  _MineMyExamPageState createState() => _MineMyExamPageState();
}

class _MineMyExamPageState extends State<MineMyExamPage> {
  List<String> _imageList = [
    "assets/images/2.0x/banner3.webp",
    "assets/images/2.0x/banner4.webp"
  ];

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () {
      _loadingMyExam();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff2f2f2),
      body: RefreshIndicator(
        notificationPredicate: (ScrollNotification notifation) {
          //该属性包含当前ViewPort及滚动位置等信息
          ScrollMetrics scrollMetrics = notifation.metrics;
          if (scrollMetrics.minScrollExtent == 0) {
            return true;
          } else {
            return false;
          }
        },
        onRefresh: () async {
          return _loadingMyExam();
        },
        child: NestedScrollView(
          //配置可折叠的头布局
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [buildSliverAppBar()];
          },
          //超出显示内容区域的Widget
          //可以是一个TabBarView来结合TabBar使用
          body: buildListView(),
        ),
      ),
    );
  }

  buildSliverAppBar() {
    return SliverAppBar(
      title: Text("我的考试"),
      //标题居中
      centerTitle: true,
      //当此值为true时 SliverAppBar title 会固定在页面顶部
      //当此值为fase时 SliverAppBar title 会随着滑动向上滑动
      pinned: true,

      //当pinned属性值为true时才会起作用
      //floating 为true时滑动到顶部 title会隐藏
      //         为false时 title 不会隐藏
      floating: false,

      //当snap配置为true时，向下滑动页面，SliverAppBar（
      // 以及其中配置的flexibleSpace内容）会立即显示出来，

      //反之当snap配置为false时，向下滑动时，
      // 只有当ListView的数据滑动到顶部时，SliverAppBar才会下拉显示出来。
      snap: false,
      //展开的高度
      expandedHeight: 140,
      //AppBar下的内容区域
      flexibleSpace: FlexibleSpaceBar(
        //背景
        //在这里直接使用的是一个图片
        background: buildSwiper(),
      ),
    );
  }

  Widget buildSwiper() {
    return Container(
      padding: EdgeInsets.only(top: 84),
      child: Row(
        children: [
          buildColumnItem(
            "assets/images/2.0x/exam_3.png",
            "常规机考",
            ExampPcTestPage(),
          ),
          buildColumnItem(
            "assets/images/2.0x/exam_1.png",
            "机考记录",
            MyPcExamRecoderPage(),
          ),
          buildColumnItem(
            "assets/images/2.0x/exam_2.png",
            "我的积分记录",
            MyScorePage(
              scoreRankType: ScoreRankType.integralStatisticsRecoder,
            ),
          ),
          // buildColumnItem(
          //   "assets/images/2.0x/exam_2.png",
          //   "机考排名",
          //   MyScorePage(
          //     scoreRankType: ScoreRankType.score,
          //   ),
          // ),
        ],
      ),
    );
  }

  List<BeanExamBean> _data = [];
  bool _isLoading = true;

  buildListView() {
    if (_isLoading) {
      return Center(
        child: LoadingPage(),
      );
    }

    if (_data.length == 0) {
      return Center(
        child: NoDataWidget(
          text: "暂无可参与的考试",
          clickCallBack: () {
            _isLoading = true;
            setState(() {});
            _loadingMyExam();
          },
        ),
      );
    }

    return ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: _data.length,
        itemBuilder: (BuildContext context, int index) {
          BeanExamBean examBean = _data[index];
          return ColorFiltered(
            colorFilter: ColorFilter.mode(
                //动态生成过滤颜色
                examBean.isClose == 0 ? Colors.transparent : Colors.black,
                //过滤模式
                BlendMode.color),
            child: Container(
              margin: EdgeInsets.only(top: 8),
              padding: EdgeInsets.all(12),
              color: Colors.white,
              child: InkWell(
                onTap: () {
                  NavigatorUtils.pushPage(
                      context, MineMyExamDetailsPage(examBean: examBean));
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          height: 16,
                          width: 3,
                          decoration: BoxDecoration(
                              color: Colors.green,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(4))),
                          margin: EdgeInsets.only(right: 10, top: 4),
                        ),
                        Expanded(
                          child: Text(
                            "${examBean.examTitle}",
                            style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 16,
                                color: Color(0xff444444)),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(right: 10, top: 4),
                          padding: EdgeInsets.only(left: 4, right: 4),
                          decoration: BoxDecoration(
                              gradient: LinearGradient(
                                  colors: [Colors.green, Colors.blue]),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2))),
                          child: Text(
                            "${examBean.isClose == 1 ? "考试已结束" : (examBean.isOpen == 0 ? "考试已开启" : "考试未开启")}",
                            style: TextStyle(fontSize: 10, color: Colors.white),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 4),
                          padding: EdgeInsets.only(left: 4, right: 4),
                          decoration: BoxDecoration(
                              gradient: LinearGradient(
                                  colors: [Colors.green, Colors.blue]),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2))),
                          child: Text(
                            "v1版经典考试",
                            style: TextStyle(fontSize: 10, color: Colors.white),
                          ),
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 14, top: 12),
                      child: Text(
                        "开始考试时间 ${examBean.openTime}",
                        style: TextStyle(
                          color: Color(0xff888888),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 14, top: 6),
                      child: Text(
                        "结束考试时间 ${examBean.closeTime}",
                        style: TextStyle(
                          color: Color(0xff888888),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 14, top: 6),
                      child: Row(
                        children: [
                          Text(
                            "考试时间 ${examBean.examTim} 分钟",
                            style: TextStyle(
                              color: Color(0xff888888),
                            ),
                          ),
                          Text(
                            "及格分数 ${examBean.examPercent} 分",
                            style: TextStyle(
                              color: Color(0xff888888),
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  ///加载我的考试列表
  Future<bool> _loadingMyExam() async {
    ResponseInfo statisRresponseInfo =
        await DioUtils.instance.postRequest(url: HttpHelper.pcTestExamClass);
    List<BeanExamBean> _list = [];
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data;
      list.forEach((element) {
        _list.add(BeanExamBean.fromMap(element));
      });
      _data = _list;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
    }
    _isLoading = false;
    if (mounted) {
      setState(() {});
    }
    return true;
  }

  ///[imageName]图标名称 [text]图标下的文案 [child]点击跳转的子页面
  Widget buildColumnItem(String imageName, String text, Widget child) {
    return Expanded(
      child: InkWell(
        onTap: () {
          NavigatorUtils.pushPage(context, child);
        },
        child: Container(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                imageName,
                width: 40,
              ),
              Text("$text")
            ],
          ),
        ),
      ),
    );
  }
}
